#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_ERR);
$dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
$oaWebDb = OpDbModel::getInstance($dbConfig, $logger);

$sql = "SELECT * FROM app_pay_server ORDER BY id";
$rows = $oaWebDb->query($sql);
foreach ($rows as $row) {
    $id = (int) $row['id'];
    if (!empty($row['addr'])) {
        $logger->info("addr already set: id-$id, addr-{$row['addr']}");
        continue;
    }
    if ($row['type'] == OaAppServerModel::PAY_SERVER_TYPE_URL) {
	    $addr = "{$row['protocol']}://{$row['ip']}";
	    if (!empty($row['port'])) {
	        $addr .= ":{$row['port']}";
	    } 
	    if (!empty($row['path'])) {
	        $addr .= "/{$row['path']}";
	    }
	} else if ($row['type'] == OaAppModel::PAY_SERVER_TYPE_SOCKET) {
		$addr = "{$row['ip']}:{$row['port']}";
	} else {
		$addr = '';
	}
    $sql = "UPDATE app_pay_server SET addr=" . escapeInputValue($addr) . " WHERE id=$id";
    if (!$oaWebDb->exec($sql)) {
        $logger->err("update failed: id-$id, addr-$addr");
        break;
    } else {
        $logger->info("update succeed: id-$id, addr-$addr");
    }
}